package com.geping.etl.common.controller;

import com.geping.etl.common.exceptoin.NoAccessRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/***
 * 异常统一处理
 * @author liang.xu
 * @date 2021.5.6
 */
@Controller
@ControllerAdvice
public class ExceptionController implements ErrorController {

    private static Logger logger = LoggerFactory.getLogger(ExceptionController.class);

    @Autowired
    private ErrorAttributes error;// 用来获取当前异常信息

    @RequestMapping("error") // 这里的error不能修改,详情看BasicErrorController源码,主要用来捕获404异常
    public String handleError(HttpServletRequest request, HttpServletResponse response) {
        WebRequest webRequest = new ServletWebRequest(request);
        Map<String, Object> error_attributes = error.getErrorAttributes(webRequest, false);
        logger.error("error---not found : ",error_attributes );
        return "common/error";
    }

    @Override
    public String getErrorPath() {
        return "";
    }

    @ExceptionHandler(value = Exception.class)
    public String error(Exception exception) {
        logger.error("error : ", exception);
        return "common/error";
    }

    @ExceptionHandler(value = NoAccessRuntimeException.class)
    public String noAccess(NoAccessRuntimeException exception) {
        logger.error("no_access : ", exception);
        return "common/no_access";
    }
}